<?php

App::uses('AppController', 'Controller');

class PaymentController extends AppController {

    public $helpers = array('Html');

    public function beforeFilter() {
        parent::beforeFilter();
        if (!$this->Session->read('Auth.User')) {
            return $this->redirect(array('controller' => 'users', 'action' => 'login'));
        }
    }

    public function index() {
        $this->loadModel('Transaction');
        $this->loadModel('User');


        $this->paginate = array(
            'conditions' => array('Transaction.user_id' => $this->Session->read('Auth.User.id')),
            'fields' => array(
                'Transaction.*', 'User.*'
            ),
            'recursive' => -1,
            'joins' => array(
                array(
                    'table' => 'users',
                    'type' => 'left',
                    'alias' => 'User',
                    'conditions' => array('Transaction.user_id = User.id')
                )
            ),
            'limit' => 25,
            'order' => array('Transaction.id' => 'desc')
        );

        // we are using the 'Admin' model
        $rows = $this->paginate('Transaction');

        // pass the value to our view.ctp
        $this->set('rows', $rows);
    }

    public function add() {
        $this->loadModel('AuthorizeSettings');
        $this->loadModel('Transaction');
        $au_settings = $this->AuthorizeSettings->find('first');
        if (!$au_settings) {
            $this->Session->setFlash('Not found payment method', 'default', array(), 'bad');
        } else {
            if ($this->request->is(array('post', 'put'))) {
                $name_on_card = $this->request->data['name_on_card'];
                $cc_number = $this->request->data['cc_number'];
                $ccv = $this->request->data['ccv'];
                $ed_month = $this->request->data['ed_month'];
                if ($ed_month < 10) {
                    $ed_month = '0' . $ed_month;
                }
                $ed_year = $this->request->data['ed_year'];
                $ed_year = substr($ed_year, 2, 2);

                //post
                if ($au_settings['AuthorizeSettings']['test_mode'])
                    $post_url = "https://test.authorize.net/gateway/transact.dll";
                else
                    $post_url = "https://secure.authorize.net/gateway/transact.dll";

                $post_values = array(
                    "x_login" => $au_settings['AuthorizeSettings']['api_login_id'], //API_LOGIN_ID
                    "x_tran_key" => $au_settings['AuthorizeSettings']['transaction_key'], //TRANSACTION_KEY
                    "x_version" => "3.1",
                    "x_delim_data" => "TRUE",
                    "x_delim_char" => "|",
                    "x_relay_response" => "FALSE",
                    "x_type" => strtoupper($au_settings['AuthorizeSettings']['payment_action']), //AUTH_CAPTURE, AUTH_ONLY 
                    "x_method" => "CC",
                    "x_card_num" => $cc_number,
                    "x_exp_date" => $ed_month . $ed_year,
                    "x_amount" => $au_settings['AuthorizeSettings']['price'],
                    "x_description" => "Sample Transaction"
                );

                $post_string = "";
                foreach ($post_values as $key => $value) {
                    $post_string .= "$key=" . urlencode($value) . "&";
                }
                $post_string = rtrim($post_string, "& ");

                $request = curl_init($post_url);
                curl_setopt($request, CURLOPT_HEADER, 0);
                curl_setopt($request, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($request, CURLOPT_POSTFIELDS, $post_string);
                curl_setopt($request, CURLOPT_SSL_VERIFYPEER, FALSE);
                $post_response = curl_exec($request);
                curl_close($request);

                $response_array = explode($post_values["x_delim_char"], $post_response);

                if ($response_array[0] == 1) {
                    $this->Transaction->create();
                    $data = array(
                        'user_id' => $this->Session->read('Auth.User.id'),
                        'payment' => 'Authorize',
                        'transaction_id' => $response_array[6],
                        'amount' => $response_array[9],
                        'currency' => 'USD',
                        'payment_status' => 'Success',
                        'date_paid' => date("Y-m-d H:i:s"),
                    );
                    $this->Transaction->save($data);
                    $this->Session->setFlash($response_array[3], 'default', array(), 'good');
                    return $this->redirect(array('action' => 'success'));
                }else{
                    $this->Session->setFlash($response_array[3], 'default', array(), 'bad');
                }
            }

            $this->set('au_settings', $au_settings);
        }
    }
    
    public function success() {
        
    }

}
